package com.feihao.zhou.workTest;


import java.util.HashMap;
import java.util.function.BiConsumer;

/**
 * 2. 分析以下需求，并用代码实现：
 * (1)统计每个单词出现的次数
 * (2)有如下字符串"If you want to change your fate I think you must come to the dark horse to learn java"(用空格间隔)
 * (3)打印格式：
 * to=3
 * think=1
 * you=2
 * //........
 */
public class Test2 {
    public static void main(String[] args) {
        String s = "If you want to change your fate I " +
                "think you must come to the dark horse to learn java";

        //先将字符串根据空格转为数组：
        String[] strings = s.split(" ");

        //遍历取出数组元素的每个首字母，添加到set集合；
        HashMap<String, Integer> map = new HashMap<>();
//        int i = 1;
        //遍历数组：
        for (String string : strings) {
            if (map.containsKey(string)) {
                //获取这个元素的次数：
                Integer integer = map.get(string);
                //再设置回去：
                integer++;
                map.put(string,integer);
            } else {
                map.put(string, 1);
            }
        }

        //遍历打印集合map:
        map.forEach(new BiConsumer<String, Integer>() {
            @Override
            public void accept(String s, Integer integer) {
                System.out.println(s + "=" + integer);
            }
        });
    }
}
